package com.proposition.web.paper;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.proposition.commons.constant.ErrorCode;
import com.proposition.commons.constant.ExamCategory;
import com.proposition.commons.constant.PaperPermission;
import com.proposition.commons.enums.PaperPattern;
import com.proposition.commons.enums.PaperType;
import com.proposition.commons.exam.bean.ExamPaperSearchItem;
import com.proposition.commons.exam.vo.ExamVO;
import com.proposition.commons.model.*;
import com.proposition.exam.service.IServiceExamManage;
import com.proposition.paper.service.PaperAddStrategy;
import com.proposition.paper.service.PaperExamService;
import com.proposition.paper.service.PaperService;
import com.proposition.paper.service.PaperStrategyService;
import com.proposition.support.annotation.LogAnnotation;
import com.proposition.support.utils.Rest;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 人工组卷控制器
 *
 * @author 杨凯
 * @create 2018-01-31 15:56
 **/
@Slf4j
@Controller
@RequestMapping("/person")
public class PaperPersonController {

	@Autowired
	private PaperService paperService;

	@Autowired
	private IServiceExamManage examManage;

	@Autowired
	private PaperExamService paperExamService;

	@Autowired
	private PaperStrategyService paperStrategyService;

	@Autowired
	@Qualifier("wenda")
	private PaperAddStrategy wendaStrategy;

	@Autowired
	@Qualifier("changguihua")
	private PaperAddStrategy changGuiHuaStrategy;

	@Autowired
	@Qualifier("keguanhua")
	private PaperAddStrategy keGuanHuaStrategy;


	/**
	 * 人工组卷页面
	 *
	 * @param model
	 * @return
	 */
	@RequestMapping("/index")
	@RequiresPermissions(PaperPermission.ADD_PAPER)
	public String index(Model model) {
		int strategy = paperStrategyService.getStrategyTwo().getStrategy();
		if (strategy == 0) {
			model.addAttribute("examClass", paperService.findExamClass());
			return "paper/paper-person";
		} else {
			model.addAttribute("count", paperService.getExamCount(4));
			return "paper/paper-auto";
		}
	}

	/**
	 * 根据条件获取已审核试题列表
	 *
	 * @param searchItem 条件
	 * @return
	 */
	@PostMapping(value = "/examList", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map<String, Object> getExamListByPassCheck(ExamPaperSearchItem searchItem) {
		Integer length = 7;
		Map<String, Object> map = new HashMap<>(3);
		//审核完成的试题
		searchItem.setLength(length);
		Page page = new Page(searchItem.getCurrPage(), searchItem.getLength());
		Page<ExamVO> examVOPage = examManage.selectExamPaperPage(page, searchItem);
		int totalPage = (examVOPage.getTotal() + length - 1) / length;
		map.put("examList", examVOPage.getRecords());
		map.put("totalPage", totalPage == 0 ? 1 : totalPage);
		return map;
	}

	@LogAnnotation(moduleName = "试卷模块", operate = "试卷添加")
	@PostMapping("/add")
	@ResponseBody
	public Rest addPaper(String pattern, String paperType, String exam1, String exam2, String exam3) {
		Rest.Builder rest = Rest.newBuilder();
		Subject subject = SecurityUtils.getSubject();
		//判断用户是否有添加试卷的权限
		if (!subject.isPermitted(PaperPermission.ADD_PAPER)) {
			return rest.status(ErrorCode.PERMISSION_DENIED).build();
		}
		//第一站
		if (pattern.equals(PaperPattern.WEN_DA.name())) {
			int status;
			//返回状态码
			status = wendaStrategy.firstQuestion(exam1);
			if (status != ErrorCode.SUCCESS) {
				return rest.status(status).build();
			}
			status = wendaStrategy.secondQuestion(exam2);
			if (status != ErrorCode.SUCCESS) {
				return rest.status(status).build();
			}
			status = wendaStrategy.thirdQuestion(exam3);
			if (status != ErrorCode.SUCCESS) {
				return rest.status(status).build();
			}

		} else if (pattern.equals(PaperPattern.CHANG_GUI.name())) {
			//第二站常规化
			//返回状态码
			int status;
			status = changGuiHuaStrategy.firstQuestion(exam1);
			if (status != ErrorCode.SUCCESS) {
				return rest.status(status).build();
			}
			status = changGuiHuaStrategy.secondQuestion(exam2);
			if (status != ErrorCode.SUCCESS) {
				return rest.status(status).build();
			}
			status = changGuiHuaStrategy.thirdQuestion(exam3);
			if (status != ErrorCode.SUCCESS) {
				return rest.status(status).build();
			}
		} else if (pattern.equals(PaperPattern.KE_GUAN.name())) {
			//第二站客观化
			//返回状态码
			int status;
			status = keGuanHuaStrategy.firstQuestion(exam1);
			if (status != ErrorCode.SUCCESS) {
				return rest.status(status).build();
			}
			status = keGuanHuaStrategy.secondQuestion(exam2);
			if (status != ErrorCode.SUCCESS) {
				return rest.status(status).build();
			}
			status = keGuanHuaStrategy.thirdQuestion(exam3);
			if (status != ErrorCode.SUCCESS) {
				return rest.status(status).build();
			}

		}
		paperService.paperAdd(Enum.valueOf(PaperPattern.class,pattern), Enum.valueOf(PaperType.class,paperType), exam1, exam2, exam3);
		return rest.status(ErrorCode.SUCCESS).build();
	}


	/**
	 * 获取试卷Id获取要修改试卷的数据
	 *
	 * @param paperId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.GET)
	public Map<String, Object> getPaperById(@RequestParam String paperId, HttpSession session) {
		Map<String, Object> map = new HashMap<>();
		Paper paper = paperService.selectById(paperId);
		map.put("paper", paper);
		//根据Id 获取试卷试题
		PaperExam paperExam = paperExamService.selectPaperExamByPaperId(paperId);
		String[] exam1 = paperExam.getExam1().split(",");
		String[] exam2 = paperExam.getExam2().split(",");
		String[] exam3 = paperExam.getExam3().split(",");
		//判断试卷分类
		switch (paper.getPaperPattern()) {
			//问答题
			case WEN_DA:
				//获取问答题腧穴题
				ExamAcupoint examAcupoint = new ExamAcupoint().selectOne(new EntityWrapper().eq("id", exam1[0]));
				map.put("exam1", examAcupoint);
				session.setAttribute("PAPER_EXAM1", examAcupoint);
				ExamAnswer10 answer10 = new ExamAnswer10().selectOne(new EntityWrapper().eq("id", exam2[0]));
				map.put("exam2", answer10);
				session.setAttribute("PAPER_EXAM2", answer10);
				answer10 = new ExamAnswer10().selectOne(new EntityWrapper().eq("id", exam3[0]));
				map.put("exam3", answer10);
				session.setAttribute("PAPER_EXAM3", answer10);
				break;
			//常规化
			case CHANG_GUI:
			case KE_GUAN:
				ExamAcupointAdult examAcupointAdult = null;
				ExamAcupointPediatric examAcupointPediatric = null;
				List<Object> list = new ArrayList<>();
				for (int i = 0; i < exam1.length; i++) {
					//根据试题Id 判断试题分类
					String category = exam1[i].substring(0, 2);
					if (ExamCategory.CHENG_REN_XW.equals(category)) {
						//成人穴位
						examAcupointAdult = new ExamAcupointAdult().selectOne(new EntityWrapper().eq("id", exam1[i]));
						list.add(examAcupointAdult);
					} else if (ExamCategory.ER_KE_XW.equals(category)) {
						//儿科穴位
						examAcupointPediatric = new ExamAcupointPediatric().selectOne(new EntityWrapper().eq("id", exam1[i]));
						list.add(examAcupointPediatric);
					}

				}
				map.put("exam1", list);
				ExamAnswer10 examAnswer10 = null;
				List<ExamAnswer10> list1 = new ArrayList<>();
				for (int i = 0; i < exam2.length; i++) {
					examAnswer10 = new ExamAnswer10().selectOne(new EntityWrapper().eq("id", exam2[i]));
					list1.add(examAnswer10);
				}
				map.put("exam2", list1);
				ExamAnswer30 exam = new ExamAnswer30().selectOne(new EntityWrapper().eq("id", exam3[0]));
				map.put("exam3", exam);
				session.setAttribute("PAPER_EXAM3", exam);
				break;
			default:
				log.error("试卷修改===>试卷分类错误！");
				break;
		}
		return map;
	}


	@LogAnnotation(moduleName = "试卷模块", operate = "试卷修改")
	@PutMapping("/update")
	@ResponseBody
	public Rest updatePaper(HttpSession session, String pattern, String exam1, String exam2, String exam3, String paperId) {
		Rest.Builder rest = Rest.newBuilder();
		Subject subject = SecurityUtils.getSubject();
		if (!subject.isPermitted(PaperPermission.UPDATE_PAPER)) {
			//没有权限；
			return rest.status(401).build();
		}
		//判断用户是否有添加试卷的权限
		if (!subject.isPermitted(PaperPermission.ADD_PAPER)) {
			return rest.status(ErrorCode.PERMISSION_DENIED).build();
		}

		if (pattern.equals(PaperPattern.WEN_DA.name())) {
			//第一站
			int status;
			ExamAcupoint acupoint = (ExamAcupoint) session.getAttribute("PAPER_EXAM1");
			if (!acupoint.getId().equals(exam1)) {
				//检测第一题是否正确 (返回状态码)
				status = wendaStrategy.firstQuestion(exam1);
				if (status != ErrorCode.SUCCESS) {
					return rest.status(status).build();
				}
			}
			ExamAnswer10 examAnswer10 = (ExamAnswer10) session.getAttribute("PAPER_EXAM2");
			if (!examAnswer10.getId().equals(exam2)) {
				//检测第二题是否正确 (返回状态码)
				status = wendaStrategy.secondQuestion(exam2);
				if (status != ErrorCode.SUCCESS) {
					return rest.status(status).build();
				}
			}
			ExamAnswer10 answer10 = (ExamAnswer10) session.getAttribute("PAPER_EXAM3");
			if (!answer10.getId().equals(exam3)) {
				//检测第三题是否正确 (返回状态码)
				status = wendaStrategy.thirdQuestion(exam3);
				if (status != ErrorCode.SUCCESS) {
					return rest.status(status).build();
				}
			}

		} else if (pattern.equals(PaperPattern.CHANG_GUI.name())) {
			//第二站
			int status;
			//检测第一题是否正确(返回状态码)
			status = changGuiHuaStrategy.firstQuestion(exam1);
			if (status != ErrorCode.SUCCESS) {
				return rest.status(status).build();
			}
			//检测第二题是否正确(返回状态码)
			status = changGuiHuaStrategy.secondQuestion(exam2);
			if (status != ErrorCode.SUCCESS) {
				return rest.status(status).build();
			}
			ExamAnswer30 answer30 = (ExamAnswer30) session.getAttribute("PAPER_EXAM3");
			if (!answer30.getId().equals(exam3)) {
				//检测第三题是否正确(返回状态码)
				status = changGuiHuaStrategy.thirdQuestion(exam3);
				if (status != ErrorCode.SUCCESS) {
					return rest.status(status).build();
				}
			}

		} else if (pattern.equals(PaperPattern.KE_GUAN.name())) {
			//第二站客观化
			int status;
			//检测第一题是否正确(返回状态码)
			status = keGuanHuaStrategy.firstQuestion(exam1);
			if (status != ErrorCode.SUCCESS) {
				return rest.status(status).build();
			}
			//检测第二题是否正确(返回状态码)
			status = keGuanHuaStrategy.secondQuestion(exam2);
			if (status != ErrorCode.SUCCESS) {
				return rest.status(status).build();
			}
			ExamAnswer30 answer30 = (ExamAnswer30) session.getAttribute("PAPER_EXAM3");
			if (!answer30.getId().equals(exam3)) {
				//检测第三题是否正确(返回状态码)
				status = keGuanHuaStrategy.thirdQuestion(exam3);
				if (status != ErrorCode.SUCCESS) {
					return rest.status(status).build();
				}
			}
		}
		PaperExam paperExam = new PaperExam();
		paperExam.setPaperId(paperId);
		paperExam.setExam1(exam1);
		paperExam.setExam2(exam2);
		paperExam.setExam3(exam3);
		paperExamService.update(paperExam, new EntityWrapper<PaperExam>().where("paper_id={0}", paperId));
		return rest.status(200).build();
	}


	/**
	 * 根据站类型 和试卷AB获取试卷编号
	 *
	 * @param paperPattern
	 * @param paperType
	 * @return
	 */
	@ResponseBody
	@PostMapping("/generatePaperNumber")
	public Map<String, Object> generatePaperNumber(String paperPattern, String paperType) {
		Map<String, Object> map = new HashMap<>();
		try {
			String paperNum = paperService.generatePaperNumber(Enum.valueOf(PaperPattern.class,paperPattern), Enum.valueOf(PaperType.class,paperType));
			map.put("paperNum", paperNum);
		} catch (Exception e) {
			log.error("试卷模块===>生成试卷编号异常[{}]", e.getMessage());
		}
		return map;
	}

}
